import React from 'react';
import {Tree, Input, Button, Pagination, message} from 'antd';
// TODO: 1. 引入 SideMenu组件
// import styles from './style/index.less';
import styles from '../view/style/index.less';

const {Search} = Input;
const {TreeNode, DirectoryTree} = Tree;
import {connect} from 'pipenet-core/lib/react';

const url = window.g_ctx.getServiceByName('HOME_SVR');

// 引入预览详情页
import DetailPage from '../../common/detailPage/index';

// 引入图片
import img2 from '../images/2.png';
import {
  getAttachList,
  getAttachTypeData,
  queryInfoDetali,
  getDownLoadAttachment,
  getDownUrl,
} from '../service/attach';


// TODO: 转换函数：将获取的数据转换为 SideMenu组件需要的结构
/**
 * 将获取的数据转换为 SideMenu组件需要的结构
 * @param data
 * @return {{img: string, children: *, title: string, key: number}[]}
 */
function toLocalTree(data) {
  const sum = data.reduce((acc, c) => acc + c.totalNum, 0);
  return [
    {
      title: `政策法规(${sum})`,
      key: -1,
      img: '',
      isRoot: true,
      children: data.map(i => {
        return {
          key: i.code,
          title: `${i.name}(${i.totalNum})`,
          // TODO: 图片, 与需求方确认方案（使用默认图片，还是其他的方案）
          img: '',
          children: [],
        };
      }),
    },
  ]
}

// TODO: 这个model已经没有使用了， 可以移除
@connect(({policy}) => ({}))
export default class View extends React.Component {
  state = {
    // TODO: 这里sum就不需要了，
    sum: 0,
    currentType: null,
    treeData: [],
    selectedKeys: [],
    // 初始化选中根节点
    currentKey: -1,
    attachList: [],
    initialized: false,
    total: 0,
    page: 1,
    pageSize: 5,
    searchKeywords: '',
    isShowTab: true,
    recond: {},
  };

  componentDidMount() {
    this.loadTreeData();
  }

  loadTreeData = async () => {
    // 加载左侧分类数据
    const res = await getAttachTypeData();
    const {data} = res;
    if (!data.length) {
      return;
    }
    const [{code}] = data;
    this.setState(
      {
        // TODO: 这里selectedKeys需要转换为 SideMenu使用的defaultKey，
        // selectedKeys: [String(code)],
        // TODO: 标记初始化完成
        initialized: true,
        currentKey: code,
        currentType: code,
        treeData: toLocalTree(data),
        // TODO: 这里sum就不需要了，
        // sum: data.reduce((acc, c) => acc + c.totalNum, 0),
      },
      () => {
        this.loadAttachList();
      }
    );
  };

  loadAttachList = async () => {
    const {currentType: typeCode, pageSize, page, searchKeywords} = this.state;
    try {
      const res = await getAttachList({
        pageSize,
        page,
        title: searchKeywords,
        typeCode,
      });
      const {total, records} = res.data;
      this.setState({
        attachList: records,
        total,
      });
    } catch (e) {
      message.error(e.message);
    }
  };

  // 修改页码变化
  handlePageChange = (page, pageSize) => {
    this.setState({page, pageSize}, () => {
      this.loadAttachList();
    });
  };

  handleSearchKeywordsChange = e => {
    this.setState({searchKeywords: e.currentTarget.value});
  };

  // 返回上一级列表页面
  handleGoBack = () => {
    this.setState({
      isShowTab: true,
    });
  };

  // 预览功能
  handlePreview = async v => {
    try {
      const {code, data, codeMessage} = await queryInfoDetali({
        id: v.id,
      });
      if (code === -1) {
        return message.error(codeMessage);
      }
      this.setState({
        isShowTab: false,
        recond: data,
      });
    } catch (e) {
      message.error(e.message);
    }
  };

  // 附件下载
  handeleDownload = async v => {
    try {
      const {code, data, message: errorMessage} = await queryInfoDetali({
        id: v.id,
      });
      if (code === -1) {
        return message.error(errorMessage);
      }
      {
        const ids = data.currentInfo.att;
        if (!ids) {
          return message.error('获取附件信息失败！');
        }
        const {code, message: errorMessage} = await getDownLoadAttachment(ids);
        if (code === -1) {
          return message.error(errorMessage);
        }
        window.open(getDownUrl(ids), '_self');
      }
    } catch (e) {
      message.error(e.message);
    }
  };

  handleSearch = () => {
    this.setState(
      {
        page: 1,
      },
      () => {
        this.loadAttachList();
      }
    );
  };

  handleSelect = (selectedKeys, e) => {
    const {currentType} = this.state;
    const {code, isRoot} = e.node.props.dataRef;
    if (isRoot || currentType === code) {
      return;
    }
    this.setState({currentType: code, page: 1, selectedKeys}, () => {
      this.loadAttachList();
    });
  };

  // TODO: 这里的 node 即为树节点的数据
  handleMenuSelect = (node) => {
    const {currentType} = this.state;
    // TODO:直接从node获取code
    const {key: code, isRoot} = node;
    if (isRoot || currentType === code) {
      return;
    }
    // TODO: 加载逻辑不变
    this.setState({currentType: code, page: 1, currentKey: code}, () => {
      this.loadAttachList();
    });
  };

  renderDetailPanel() {
    if (this.state.isShowTab) {
      return null;
    }
    return (
      <div style={{float: 'left', width: '78%', height: '100%'}}>
        <div style={{height: '100%'}}>
          <DetailPage
            goBack={this.handleGoBack}
            recond={this.state.recond}
            changeDetail={this.handlePreview}
          />
        </div>
      </div>
    );
  }

  renderAttachPanel() {
    if (!this.state.isShowTab) {
      return null;
    }
    const {searchKeywords, attachList, total, page, pageSize} = this.state;
    return (
      <div>
        <div className={styles.search}>
          <Search
            value={searchKeywords}
            onChange={this.handleSearchKeywordsChange}
            onSearch={this.handleSearch}
            enterButton
          />
        </div>

        {/* 中间主体区域 */}
        <div className={styles.box2}>
          {attachList.map(v => {
            return (
              <div className={styles.box1} key={v.id}>
                <img
                  className={styles.img}
                  src={v.coverimg ? `${url}/file/download/${v.coverimg}` : img2}
                />
                <div className={styles.title}>{v.title}</div>
                <Button
                  className={styles.btn1}
                  onClick={() => {
                    this.handlePreview(v);
                  }}
                >
                  预览
                </Button>
                <Button
                  className={styles.btn2}
                  onClick={() => {
                    this.handeleDownload(v);
                  }}
                >
                  附件下载
                </Button>
                <div className={styles.jianjei}>简介：xxxxxxxx</div>
                <div style={{fontSize: '12px'}}>
                  上传时间：{v.publishTime} &nbsp;&nbsp;大小：{v.typeCode}
                </div>
                <div className={styles.author}>上传人：{v.author}</div>
              </div>
            );
          })}
        </div>

        {/* 分页 */}
        <div className={styles.page}>
          <Pagination
            total={total}
            onChange={this.handlePageChange}
            showTotal={total => `共 ${total} 条`}
            pageSize={pageSize}
            page={page}
          />
        </div>
      </div>
    );
  }

  // TODO: 保留原始方法，作备份
  renderTree() {
    const {selectedKeys, sum, treeData} = this.state;
    return (
      <DirectoryTree
        multiple={false}
        defaultExpandAll
        selectedKeys={selectedKeys}
        onSelect={this.handleSelect}
        onExpand={this.onExpand}
      >
        <TreeNode dataRef={{isRoot: true}} title={`政策法规(${sum})`} key={-1}>
          {treeData.map(item => {
            return (
              <TreeNode
                title={item.name + `(${item.totalNum})`}
                key={item.code}
                isLeaf
                dataRef={item}
              />
            );
          })}
        </TreeNode>
      </DirectoryTree>
    )
  }

  // TODO: 待实现
  renderSideMenu() {
    // TODO: 1. 引入 SideMenu组件
    // TODO: 2. 准备所需要数据 data defaultKey
    // TODO: 3. 处理onSelect事件
    const {currentKey, treeData} = this.state;
    return (
      <SideMenu data={treeData} defaultKey={currentKey} onSelect={this.handleMenuSelect} />
    )
  }

  render() {
    // TODO: 不受控处理办法
    if (!this.state.initialized) {
      return null;
    }
    return (
      <div className={styles.box}>
        <div className={styles.nav}>
          {this.renderSideMenu()}
        </div>
        <div>{this.renderAttachPanel()}</div>
        <div style={{height: '100%'}}>{this.renderDetailPanel()}</div>
      </div>
    );
  }
}
